namespace BM.Tools.WebControls.MForm.Navigation.XPath
{
    using System;

    using BM.Tools.WebControls.MForm.Navigation.XPath.NodeTests;

    /// <summary>
    /// The definition of the location step in xpath.
    /// </summary>
    public class LocationStep
    {
        /// <summary>
        /// Gets a value indicating whether the location step denotes DescendantOrSelf.
        /// </summary>
        /// <value>
        /// The denotes descendant or self.
        /// </value>
        public bool DenotesDescendantOrSelf
        {
            get
            {
                if (this is CompoundLocationStep)
                {
                    return false;
                }

                var singleLocationStep = this as SingleLocationStep;
                if (singleLocationStep == null)
                {
                    return false;
                }

                if (singleLocationStep.NodeTest is DescendantOrSelfTest)
                {
                    return true;
                }

                return false;
            }
        }

        /// <summary>
        /// Creates the location step out of its string definition
        /// </summary>
        /// <param name="locationStepText">
        /// The locationStep text.
        /// </param>
        /// <returns>
        /// the <see cref="LocationStep" /> object
        /// </returns>
        public static LocationStep Create(string locationStepText)
        {
            locationStepText = locationStepText.Trim();
            if (locationStepText.StartsWith("(", StringComparison.Ordinal) && locationStepText.EndsWith(")", StringComparison.Ordinal))
            {
                locationStepText = locationStepText.Substring(1, locationStepText.Length - 2);
            }

            if (locationStepText.IndexOf("|", StringComparison.Ordinal) != -1)
            {
                return CompoundLocationStep.Create(locationStepText);
            }

            return SingleLocationStep.Create(locationStepText);
        }
    }
}